package com.jshop.api.interceptor;

import com.jshop.api.annotation.IgnoreAuth;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 权限(Token)验证
 *
 * @date 2017-03-23 15:38
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getServletPath());
        //支持跨域请求
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "*,content-type,jshop-token");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        IgnoreAuth annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        } else {
            return true;
        }
        //如果有@IgnoreAuth注解，则不验证token
        if (annotation != null) {
            return true;
        }
        //从header中获取token
//        String token = request.getHeader(ApiConstant.LOGIN_TOKEN_KEY);
//        //如果header中不存在token，则从参数中获取token
//        if (StringUtils.isBlank(token)) {
//            token = request.getParameter(ApiConstant.LOGIN_TOKEN_KEY);
//        }
//
//        //token为空
//        if (StringUtils.isBlank(token)) {
//            throw new ApiRRException(ResultCode.UNAUTHORIZED.getMessage(), ResultCode.UNAUTHORIZED.getCode());
//        }
//        TbTokenVo tokenVo = apiTbTokenService.getToken(token);
//        if (tokenVo == null) {
//            throw new ApiRRException(ResultCode.UNAUTHORIZED.getMessage(), ResultCode.UNAUTHORIZED.getCode());
//        }
//        Date expireTime = tokenVo.getExpireTime();
//        if (expireTime.compareTo(new Date()) < 1) {
//            throw new ApiRRException(ResultCode.UNAUTHORIZED.getMessage(), ResultCode.UNAUTHORIZED.getCode());
//        }
//        request.setAttribute(ApiConstant.LOGIN_TOKEN_KEY, tokenVo);
        return true;
    }
}
